
import store from '../store'
import CryptoJS from 'crypto-js'
import expireStorage from '@/util/storeUtil.js'


const aesKey =  '0x186a0000000000'

export default {
	// 是否已登录
	isLoginedin(showTip){
		const refreshToken = expireStorage.getCache('refreshToken')
		if (!refreshToken || refreshToken.length <1 || refreshToken == 'undefined') {
			if(showTip){
				uni.showToast({
					title: '请登录',
					icon: 'none'
				});
			}
			return false;
		}
		return true;
	},
	// 初始化登录状态
	initLoginStatus() {
		const token = expireStorage.getCache('accessToken')
		if (!token || token.length < 1 || token == 'undefined') {
			const refreshToken = expireStorage.getCache('refreshToken')
			if (refreshToken && refreshToken.length > 0 && refreshToken !== 'undefined') {
				store.dispatch('RefreshToken').then(({data}) => {
					store.commit("SET_ACCESS_TOKEN", data.data.accessToken);
				}).catch((err) => {
				})
			}else{
				uni.setStorageSync('userInfo', {});
			}
		}

	},
	// 获取唯一id
	generateUniqueId() {
		let res = uni.getDeviceInfo()
		// 设备信息 设备id + 设备型号 + 操作系统及版本
		const navigatorInfo = res.deviceId + res.deviceModel + res.system
		// 设备屏幕信息
			const screenInfo = 'xx';
		// const screenInfo = screen.height + 'x' + screen.width + 'x' + screen.colorDepth;
		const timezone = '';
		// Simplified for demonstration. Consider more complex information gathering and hashing in real projects.
		const fingerprint = navigatorInfo + screenInfo + timezone;
		// Use a simple hash function for processing
		return hashFunction(fingerprint);
	},

}
function hashFunction(string) {

	let hash = 0, i, chr;
	if (string.length === 0) return hash.toString();
	for (i = 0; i < string.length; i++) {
		chr   = string.charCodeAt(i);
		hash  = ((hash << 5) - hash) + chr;
		hash |= 0;
	}

	let key  = CryptoJS.enc.Utf8.parse(aesKey);
	let content = CryptoJS.enc.Utf8.parse(hash.toString());
	let encrypted = CryptoJS.AES.encrypt(content, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
	return encrypted.toString();
}
